// package-market/pages/lottery-edit-scale/index.js
const app = getApp();
import { ACTIVITY_STATUS_VALUE } from '../../../constants/activity';
import { navBack, tipToast } from '../../../common/env';
import { arr2Obj } from '../../../common/utils';
let productId;

Page({
    data: {
        activityInfo: {},
        productInfo: {},
        productScaleMap: {},
        allAuantityModal: {
            show: false,
        },
        modifyFlag: true,
    },
    onLoad(options) {
        productId = options.productId;
        app.event.addListener('sendLotteryActivityInfo', this._handleSendActivity.bind(this));
    },
    onUnload() {
        app.event.removeListener('sendLotteryActivityInfo');
    },
    _handleSendActivity(activityInfo) {
        const productInfo = activityInfo.activityProductWithSkus.find(ps => ps.productId === productId);
        const productInfoCache = activityInfo.activityProductWithSkusCache.find(ps => ps.productId === productId);
        const productScaleMap = productInfoCache && productInfoCache.skus && productInfoCache.skus.length ? arr2Obj(productInfoCache.skus, 'productSpecId') : {};
        const modifyFlag = !activityInfo.processStatus || activityInfo.processStatus === ACTIVITY_STATUS_VALUE.draft;
        this.setData({
            modifyFlag,
            activityInfo,
            productInfo,
            productScaleMap,
        });
    },
    handleShowAllAuantityModal() {
        this.setData({
            'allAuantityModal.show': true,
        });
    },
    handleChangeAllMaximum(e) {
        const price = e.detail;
        const { productInfo } = this.data;
        const skus = productInfo.skus.map(s => {
            s.maximum = price;
            return s;
        });
        this.setData({ 'productInfo.skus': skus });
    },
    handleChangeScale(e) {
        const { productSpecId, maximum } = e.detail;
        const { productInfo } = this.data;
        const idx = productInfo.skus.findIndex(c => c.productSpecId === productSpecId);
        productInfo.skus[idx].maximum = maximum;
        this.setData({ productInfo });
    },
    handleSave() {
        const { activityInfo, productInfo } = this.data;
        const { activityProductWithSkus } = activityInfo;
        const idx = activityProductWithSkus.findIndex(ps => ps.productId === productId);
        if (!productInfo.skus.every(s => s.maximum > 0)) {
            tipToast('库存需大于0');
            return;
        }
        activityProductWithSkus[idx] = productInfo;
        app.event.trigger('getLotteryActivityInfo', activityInfo);
        navBack();
    },
})
